package com.xquant.pricing.systerm.service.task;

import com.xquant.common.engine.xPP.cxf.XQuantPPService;
import com.xquant.pricing.calc.entity.TaskLog;
import com.xquant.pricing.systerm.service.JobService;
import com.xquant.pricing.systerm.service.TaskService;
import com.xquant.pricing.utils.DateUtils;
import org.apache.commons.collections.MapUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

@Component
public class JobServiceImpl4RestTask implements JobService {
    private static final Logger LOGGER = LoggerFactory.getLogger(JobServiceImpl4RestTask.class);

    @Autowired
    private TaskService taskService;
    @Autowired
    private XQuantPPService xQuantPPService;

    @Override
    public String getJobType() {
        return "CALC_RESET_TASK";
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String jobName = MapUtils.getString(jobExecutionContext.getMergedJobDataMap(), "jobName");
        String context = MapUtils.getString(jobExecutionContext.getMergedJobDataMap(), "context");
        // 记录日志
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskName(jobName);
        taskLog.setContext(context);
        taskLog.setStatus(0);
        taskLog.setStartTime(DateUtils.getCurrentDateTimeOther());
        taskService.addTaskLog(taskLog);
        try {
            LOGGER.info(MessageFormat.format("任务 {0} 开始!,任务参数：{1}", jobName, taskLog.getContext()));
            xQuantPPService.restartAll();
            LOGGER.info("计算服务重启成功");
            taskLog.setStatus(1);
            taskLog.setResult("计算服务重启成功");
            LOGGER.info(MessageFormat.format("任务 {0} 结束!", jobName));
        } catch (Exception ex) {
            taskLog.setStatus(2);
            taskLog.setResult(ex.toString());
            LOGGER.error(MessageFormat.format("任务 {0} 失败!，原因：{1}", jobName, ex.getMessage()));
        } finally {
            taskLog.setFinishTime(DateUtils.getCurrentDateTimeOther());
            taskService.updateTaskLog(taskLog);
        }

    }
}
